<template>
	<div class="card__body-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<el-form v-show="state.showSearch" :model="state.queryParams" ref="queryFormRef" inline>
				<el-form-item label="商品名称" prop="goods_title">
					<el-input v-model="state.queryParams.goods_title" clearable placeholder="请输入商品名称" />
				</el-form-item>
				<el-form-item label="收货人姓名" prop="address_name">
					<el-input v-model="state.queryParams.address_name" clearable placeholder="请输入收货人姓名" />
				</el-form-item>
				<el-form-item label="收货人电话" prop="address_mobile">
					<el-input
						v-model="state.queryParams.address_mobile"
						@input="onVerifiyNumberIntegerAddressMobile"
						clearable
						placeholder="请输入收货人电话"
					/>
				</el-form-item>
				<el-form-item label="关联供应商" prop="supplier_id">
					<el-select
						v-model="state.queryParams.supplier_id"
						clearable
						placeholder="请输入关键字/选择供应商"
						filterable
						remote
						:remote-method="supplierIdRemoteMethod"
						remote-show-suffix
						:loading="state.supplierIdSelect.loading"
						@focus="onSupplierIdFocus"
					>
						<el-option v-for="item in state.supplierIdSelect.options" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="用户ID" prop="user_id">
					<el-input v-model="state.queryParams.user_id" @input="onVerifiyNumberIntegerUserId" clearable placeholder="请输入用户ID" />
				</el-form-item>
				<el-form-item label="用户昵称" prop="user_nickname">
					<el-input v-model="state.queryParams.user_nickname" clearable placeholder="请输入用户昵称" />
				</el-form-item>
				<el-form-item label="推荐人ID" prop="invite_id">
					<el-input v-model="state.queryParams.invite_id" clearable placeholder="请输入推荐人ID" />
				</el-form-item>
				<el-form-item label="支付时间" prop="time">
					<el-date-picker
						v-model="state.queryParams.time"
						type="datetimerange"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						format="YYYY-MM-DD HH:mm:ss"
						value-format="YYYY-MM-DD HH:mm:ss"
						:default-time="state.defaultTime"
					/>
				</el-form-item>
				<el-form-item label="父订单号" prop="order_no">
					<el-input v-model="state.queryParams.order_no" clearable placeholder="请输入父订单号" />
				</el-form-item>
				<el-form-item label="子订单号" prop="order_detail_no">
					<el-input v-model="state.queryParams.order_detail_no" clearable placeholder="请输入子订单号" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="onQuery">
						<el-icon>
							<ele-Search />
						</el-icon>
						查 询
					</el-button>
					<el-button @click="onResetQuery">
						<el-icon>
							<ele-Refresh />
						</el-icon>
						重 置
					</el-button>
				</el-form-item>
			</el-form>
			<el-row :gutter="10" class="top-block">
				<el-col :span="1.5">
					<el-button type="warning" @click="onOrderExport">导出订单</el-button>
					<el-button v-if="state.queryParams.type === 2" type="warning" @click="onOrderDeliverExport">导出待发货订单</el-button>
					<el-button type="primary" @click="onOrderDeliverImport">批量发货</el-button>
					<!-- <el-button type="info" @click="onDownload">下载快递编码信息</el-button> -->
				</el-col>
				<RightToolbar v-model:showSearch="state.showSearch" @queryTable="getList" />
			</el-row>
			<el-tabs v-model="state.queryParams.type">
				<el-tab-pane label="全部订单" :name="0" />
				<el-tab-pane label="待付款" :name="1" />
				<el-tab-pane label="待发货" :name="2" />
				<el-tab-pane label="备货中" :name="3" />
				<el-tab-pane label="待收货" :name="4" />
				<el-tab-pane label="已完成" :name="5" />
				<el-tab-pane label="已取消" :name="6" />
				<el-tab-pane label="已退款" :name="7" />
			</el-tabs>
			<el-table :data="state.tableList" v-loading="state.loading">
				<el-table-column label="订单号" align="center" prop="order" width="244">
					<template #default="{ row }">
						<el-row type="flex" justify="center">
							<div style="text-align: left">
								父订单号：{{ row.orders.order_no }}<br />
								子订单号：{{ row.orders.order_detail_no }}
							</div>
						</el-row>
					</template>
				</el-table-column>
				<el-table-column label="商品主图" align="center" prop="thumb">
					<template #default="{ row }">
						<el-avatar :src="row.orders.goods_thumb" shape="square" />
					</template>
				</el-table-column>
				<el-table-column label="商品名称" align="center" prop="orders.goods_title" />
				<el-table-column label="关联供应商" align="center" prop="orders.supplier_name" width="100" />
				<el-table-column label="商品信息" align="center" prop="good_info" width="150">
					<template #default="{ row }">
						<el-row type="flex" justify="center">
							<div style="text-align: left">
								商品规格：{{ row.orders.option_name }}<br />
								商品类型：{{ row.goods_type === 1 ? '普通商品' : '礼品商品' }}<br />
								售价：{{ row.orders.sale_price }}<br />
								购买数量：{{ row.orders.total_num }}<br />
								总售价：{{ row.orders.total_amt }}
							</div>
						</el-row>
					</template>
				</el-table-column>
				<el-table-column label="用户信息" align="center" prop="user" width="212">
					<template #default="{ row }">
						<el-row type="flex" justify="center">
							<div style="text-align: left">
								用户ID：{{ row.user_id }}<br />
								用户等级：{{ formatterIdentity(row.user_identity) }}<br />
								用户昵称：{{ row.user_nickname }}
							</div>
						</el-row>
					</template>
				</el-table-column>
				<el-table-column label="铜牌信息" align="center" prop="user_info" width="212">
					<template #default="{ row }">
						<el-row type="flex" justify="center">
							<div v-if="row.user_identity > 1">----</div>
							<div v-else style="text-align: left">
								用户ID：{{ row.one_id }}<br />
								用户等级：{{ formatterIdentity(row.one_identity) }}<br />
								用户昵称：{{ row.one_nickname }}
							</div>
						</el-row>
					</template>
				</el-table-column>
				<el-table-column label="银牌信息" align="center" prop="user_info" width="212">
					<template #default="{ row }">
						<el-row type="flex" justify="center">
							<div v-if="row.user_identity > 2">----</div>
							<div v-else style="text-align: left">
								用户ID：{{ row.two_id }}<br />
								用户等级：{{ formatterIdentity(row.two_identity) }}<br />
								用户昵称：{{ row.two_nickname }}
							</div>
						</el-row>
					</template>
				</el-table-column>
				<el-table-column label="金牌信息" align="center" prop="user_info" width="212">
					<template #default="{ row }">
						<el-row type="flex" justify="center">
							<div v-if="row.user_identity > 3">----</div>
							<div v-else style="text-align: left">
								用户ID：{{ row.three_id }}<br />
								用户等级：{{ formatterIdentity(row.three_identity) }}<br />
								用户昵称：{{ row.three_nickname }}
							</div>
						</el-row>
					</template>
				</el-table-column>
				<el-table-column label="收货信息" align="center" prop="address_info" width="166">
					<template #default="{ row }">
						<el-row type="flex" justify="center">
							<div style="text-align: left">
								收货人：{{ row.address_name }}<br />
								手机号：{{ row.address_mobile }}<br />
								所在地区：{{ row.country }}，{{ row.province }}，{{ row.city }}，{{ row.county }}<br />
								详细地址：<el-popover placement="top" title="详细地址" :width="200" trigger="hover" :content="row.address_detail">
									<template #reference>
										<el-button type="primary" link>查看</el-button>
									</template>
								</el-popover>
							</div>
						</el-row>
					</template>
				</el-table-column>
				<el-table-column label="快递信息" align="center" prop="order_info" width="218">
					<template #default="{ row }">
						<el-row type="flex" justify="center">
							<div v-if="row.orders.logistics.length" style="text-align: left">
								快递公司：{{ row.orders.logistics[0].logistics_name }}<br />
								快递单号：{{ row.orders.logistics[0].logistics_no }}<br />
								<span v-if="row.orders.logistics.length > 1">
									其他快递：<el-popover placement="top" title="其他快递" :width="296" trigger="hover">
										<el-table :data="row.orders.logistics" border>
											<el-table-column label="快递公司" align="center" width="100" prop="logistics_name" />
											<el-table-column label="快递单号" align="center" width="170" prop="logistics_no" />
										</el-table>
										<template #reference>
											<el-button type="primary" link>查看</el-button>
										</template>
									</el-popover>
								</span>
							</div>
							<div v-else>----</div>
						</el-row>
					</template>
				</el-table-column>
				<el-table-column label="订单信息" align="center" prop="order_info" width="200">
					<template #default="{ row }">
						<el-row type="flex" justify="center">
							<div style="text-align: left">
								运费：{{ Number(row.orders.trans_amt) ? row.orders.trans_amt : '包邮' }}<br />
								支付金额(含运费)：{{ row.orders.pay_amt }}<br />
								<span v-if="row.orders.refund_state">退款金额：{{ row.orders.pay_amt }}</span>
							</div>
						</el-row>
					</template>
				</el-table-column>
				<el-table-column label="状态" align="center" prop="state" width="150">
					<template #default="{ row }">
						<el-row type="flex" justify="center">
							<div style="text-align: left">
								订单状态：{{ formatterState(row) }}<br />
								<template v-if="row.orders.refund_state">退款状态：{{ formatterRefundState(row) }}<br /></template>
								<template v-if="isOrderCompleted(row)">结算状态：{{ formatterSettleState(row) }}</template>
							</div>
						</el-row>
					</template>
				</el-table-column>
				<el-table-column label="支付时间" align="center" prop="orders.pay_time" :formatter="formatterPayTime" width="100" />
				<el-table-column label="操作" align="center" prop="operation" fixed="right">
					<template #default="{ row }">
						<el-button type="primary" @click="onOrderTimeline(row)" link>查看时间轴</el-button>
						<el-button type="primary" v-if="isOrderRefund(row)" @click="onOrderRefund(row)" link>退款</el-button>
						<el-popconfirm v-if="!row.pay_state" title="您确定取消该订单？此操作不可撤回" @confirm="onOrderCancel(row)" width="180px">
							<template #reference>
								<el-button type="primary" link> 取消订单 </el-button>
							</template>
						</el-popconfirm>
						<el-button
							type="primary"
							v-if="isOrderDeliver(row)"
							@click="onOrderDeliver({ type: 'add', title: `「${row.orders.order_detail_no}」订单发货` }, row)"
							link
						>
							发货
						</el-button>
						<el-button
							type="primary"
							v-if="isOrderDeliver1(row)"
							@click="onOrderDeliver({ type: 'edit', title: `「${row.orders.order_detail_no}」订单补充发货` }, row)"
							link
						>
							补充发货
						</el-button>
						<el-popconfirm v-if="isOrderReceipt(row)" title="该订单用户已签收您确认收货？此操作不可撤回" @confirm="onOrderReceipt(row)" width="200px">
							<template #reference>
								<el-button type="primary" link> 确认收货 </el-button>
							</template>
						</el-popconfirm>
					</template>
				</el-table-column>
			</el-table>
			<PaginationComponent
				v-if="state.total"
				:total="state.total"
				v-model:page="state.queryParams.pageNum"
				v-model:limit="state.queryParams.pageSize"
				@pagination="getList"
			/>
		</el-card>
		<OrderDeliverImportDialog ref="orderDeliverImportDialogRef" />
		<OrderDeliveryDialog ref="orderDeliveryDialogRef" />
		<OrderRefundDialog ref="orderRefundDialogRef" />
		<OrderTimelineDialog ref="orderTimelineDialogRef" />
	</div>
</template>

<script setup lang="ts" name="order">
import { ElLoading, ElMessage } from 'element-plus';
import { defineAsyncComponent, inject, onMounted, reactive, ref, watch } from 'vue';

import { goodsApi, orderApi } from '/@/api';
import { verifiyNumberInteger1 } from '/@/utils/toolsValidate';
import { handleDownloadByName } from '/@/utils/utils';
import { timeDictionary } from '/@/utils/dictionary';

const OrderDeliverImportDialog = defineAsyncComponent(() => import('./dialog/orderDeliverImportDialog.vue'));
const OrderDeliveryDialog = defineAsyncComponent(() => import('./dialog/orderDeliveryDialog.vue'));
const OrderRefundDialog = defineAsyncComponent(() => import('./dialog/orderRefundDialog.vue'));
const OrderTimelineDialog = defineAsyncComponent(() => import('./dialog/orderTimelineDialog.vue'));

const Dayjs: any = inject('dayjs');
const GoodsApi = goodsApi();
const OrderApi = orderApi();
// 定义变量内容
const state = reactive({
	showSearch: true,
	queryParams: {
		goods_title: '',
		address_name: '',
		address_mobile: '',
		supplier_id: '',
		user_id: '',
		user_nickname: '',
		invite_id: '',
		time: [],
		order_no: '',
		order_detail_no: '',
		type: 0,
		pageNum: 1,
		pageSize: 10,
	},
	tableList: [],
	loading: false,
	total: 0,
	supplierIdSelect: {
		loading: false,
		options: [] as any,
	},
	defaultTime: [
		new Date(Dayjs().year(), Dayjs().month(), Dayjs().date(), 0, 0, 0),
		new Date(Dayjs().year(), Dayjs().month(), Dayjs().date(), 23, 59, 59),
	],
});
const queryFormRef = ref();
const orderDeliveryDialogRef = ref();
const orderDeliverImportDialogRef = ref();
const orderTimelineDialogRef = ref();
const orderRefundDialogRef = ref();
const exportLoadingRef = ref();

onMounted(() => {
	getList();
});

watch(
	() => state.queryParams.type,
	() => onQuery()
);

/********** 触发事件 **********/
// 收货人电话过滤
const onVerifiyNumberIntegerAddressMobile = (val: string) => {
	state.queryParams.address_mobile = verifiyNumberInteger1(val);
};
// 关联供应商获取焦点
const onSupplierIdFocus = () => {
	if (state.queryParams.supplier_id) return;
	_goodsSelectSupplier({ pageNum: 1, pageSize: 10 });
};
// 用户ID过滤
const onVerifiyNumberIntegerUserId = (val: string) => {
	state.queryParams.user_id = verifiyNumberInteger1(val);
};
// 查询
const onQuery = () => {
	state.queryParams.pageNum = 1;
	getList();
};
// 重置查询
const onResetQuery = () => {
	queryFormRef.value.resetFields();
	onQuery();
};
// 导出订单
const onOrderExport = () => {
	exportLoadingRef.value = ElLoading.service({
		lock: true,
		text: '正在导出，请耐心等待...',
		background: 'rgba(0, 0, 0, 0.7)',
	});
	_exportFinance({
		...state.queryParams,
		start_time: state.queryParams.time ? state.queryParams.time[0] : '',
		end_time: state.queryParams.time ? state.queryParams.time[1] : '',
	});
};
// 导出待发货订单
const onOrderDeliverExport = () => {
	exportLoadingRef.value = ElLoading.service({
		lock: true,
		text: '正在导出，请耐心等待...',
		background: 'rgba(0, 0, 0, 0.7)',
	});
	_orderExportInfoNew({
		...state.queryParams,
		type: 2,
		start_time: state.queryParams.time ? state.queryParams.time[0] : '',
		end_time: state.queryParams.time ? state.queryParams.time[1] : '',
	});
};
// 取消订单
const onOrderCancel = (row: any) => {
	_orderCancel({ order_id: row.id });
};
// 批量发货
const onOrderDeliverImport = () => {
	orderDeliverImportDialogRef.value.openDialog(() => getList());
};
// 单个发货
const onOrderDeliver = (data: Object, row: any) => {
	orderDeliveryDialogRef.value.openDialog(data, row, () => getList());
};
// 确认收货
const onOrderReceipt = (row: any) => {
	_orderReceipt({ order_detail_id: row.orders.id });
};
// 发货前退款
const onOrderRefund = (row: any) => {
	orderRefundDialogRef.value.openDialog(row, () => getList());
};
// 查看订单时间轴
const onOrderTimeline = (row: any) => {
	orderTimelineDialogRef.value.openDialog(row);
};

/********** 方法事件 **********/
// 刷新列表
const getList = () => {
	state.loading = true;
	_orderList({
		...state.queryParams,
		start_time: state.queryParams.time ? state.queryParams.time[0] : '',
		end_time: state.queryParams.time ? state.queryParams.time[1] : '',
	});
};
// 关联供应商搜索选择
const supplierIdRemoteMethod = (query: string) => {
	if (!query) return;
	_goodsSelectSupplier({ pageNum: 1, pageSize: 10, title: query });
};
// 用户身份字典
const formatterIdentity = (identity: number) => {
	switch (identity) {
		case 0:
			return '普通用户';
		case 1:
			return '铜牌会员';
		case 2:
			return '银牌会员';
		case 3:
			return '金牌会员';
		default:
			return '未知错误';
	}
};
// 状态字典
const formatterState = (row: any) => {
	switch (row.pay_state) {
		case 0:
			return '待支付';
		case 1:
			switch (row.orders.delivery_state) {
				case 0:
					switch (row.orders.refund_state) {
						case 0:
						case 1:
						case 3:
							return '待发货';
						case 2:
							return '已关闭';
						default:
							return '未知错误3';
					}
				case 1:
					return '备货中';
				case 2:
					return '待收货';
				case 3:
					return '已完成';
				default:
					return '未知错误2';
			}
		case 2:
			return '已取消';
		default:
			return '未知错误1';
	}
};
// 退款状态字典
const formatterRefundState = (row: any) => {
	switch (row.orders.refund_state) {
		case 0:
			return '未退款';
		case 1:
			return '退款中';
		case 2:
			return '退款完成';
		case 3:
			return '退款失败';
		default:
			return '未知错误';
	}
};
// 结算状态字典
const formatterSettleState = (row: any) => {
	switch (row.orders.settle_state) {
		case 1:
			return '待结算';
		case 2:
			return '已结算';
		default:
			return '未知状态';
	}
};
// 下单时间字典
const formatterPayTime = (row: any) => {
	return timeDictionary(row.orders.pay_time);
};
// 是否确发货
const isOrderDeliver = (row: any) => {
	if (row.pay_state === 1) {
		switch (row.orders.delivery_state) {
			case 0:
				switch (row.orders.refund_state) {
					case 0:
					case 1:
					case 3:
						return true;
					default:
						return false;
				}
			case 1:
				return true;
			default:
				return false;
		}
	}
	return false;
};
// 是否补充发货
const isOrderDeliver1 = (row: any) => {
	if (row.pay_state === 1) {
		switch (row.orders.delivery_state) {
			case 2:
				return true;
			default:
				return false;
		}
	}
	return false;
};
// 是否确认收货
const isOrderReceipt = (row: any) => {
	if (row.orders.delivery_state === 2) {
		return true;
	} else {
		return false;
	}
};
// 是否退款
const isOrderRefund = (row: any) => {
	switch (row.pay_state) {
		case 1:
			switch (row.orders.delivery_state) {
				case 0:
					switch (row.orders.refund_state) {
						case 0:
						case 3:
							return true;
						default:
							return false;
					}
				default:
					return false;
			}
		default:
			return false;
	}
};
// 是否已完成
const isOrderCompleted = (row: any) => {
	if (row.orders.delivery_state === 3) {
		return true;
	} else {
		return false;
	}
};

/********** 网络事件 **********/
// 选择供应商
const _goodsSelectSupplier = (params: Object) => {
	state.supplierIdSelect.loading = true;
	GoodsApi.goodsSelectSupplier(params)
		.then((res) => {
			state.supplierIdSelect.options = res.data.list;
			state.supplierIdSelect.loading = false;
		})
		.catch(() => (state.supplierIdSelect.loading = false));
};
// 订单列表
const _orderList = (params: Object) => {
	OrderApi.orderList(params)
		.then((res) => {
			state.tableList = res.data.list.map((item: any) => {
				return {
					...item,
					orders: {
						...item.orders,
						logistics: item.orders.logistics.reverse(),
					},
				};
			});
			state.total = res.data.info.total;
			state.loading = false;
		})
		.catch(() => (state.loading = false));
};
// 取消订单
const _orderCancel = (params: Object) => {
	OrderApi.orderCancel(params).then(() => {
		ElMessage.success('操作成功！');
		getList();
	});
};
// 确认收货
const _orderReceipt = (params: Object) => {
	OrderApi.orderReceipt(params).then(() => {
		ElMessage.success('操作成功！');
		getList();
	});
};
// 导出财务订单文件
const _exportFinance = (params: Object) => {
	OrderApi.exportFinance(params)
		.then((res) => {
			exportLoadingRef.value.close();
			handleDownloadByName(res.data.info.export_info.url, '订单数据', false);
		})
		.catch(() => {
			exportLoadingRef.value.close();
		});
};
// 导出待发货订单(新)
const _orderExportInfoNew = (params: Object) => {
	OrderApi.orderExportInfoNew(params)
		.then((res) => {
			exportLoadingRef.value.close();
			handleDownloadByName(res.data.info.export_info.url, '待发货订单', false);
		})
		.catch(() => {
			exportLoadingRef.value.close();
		});
};
</script>
